const SFCScriptBlock = require('@vue/compiler-sfc')
const SFCDescriptor = require('@vue/compiler-sfc')
const {getPropsNode} = require("./relNode");

/**
 * 获取 props 文本内容
 * @param {SFCScriptBlock} scriptBlock vue解析后的Script块
 * @param {SFCDescriptor} descriptor vue格式化后的代码
 * @return {string}
 */
function getPropsText(scriptBlock, descriptor) {
    const propsNode = getPropsNode(scriptBlock)
    if (!propsNode) return ''
    return descriptor.scriptSetup.content.substring(propsNode.loc.start.index, propsNode.loc.end.index)
}

/**
 * 解析属性注释
 * @param {string} content 属性内容
 * @return {{[string]: string}}
 */
function relPropsAnnotationByText(content) {
    const lines = content.split('\n');
    const jsonObject = {};

    lines.forEach((line, index) => {
        const commentIndex = line.indexOf('//');
        if (commentIndex !== -1) {
            jsonObject[lines[index + 1].split(':')[0].trim().replaceAll('"', '')] = line.substring(commentIndex + 2).trim();
        }
    });

    return jsonObject;
}

/**
 * 解析属性注释，通过字符串形式获取，实际上可以通过 scriptBlock 中的 leadingComments 获取
 * @param {SFCScriptBlock} scriptBlock vue解析后的Script块
 * @param {SFCDescriptor} descriptor vue格式化后的代码
 * @return {{[string]: string}|null}
 */
function relPropsAnnotation(scriptBlock, descriptor) {
    const propsText = getPropsText(scriptBlock, descriptor)
    if (!propsText) return null
    return relPropsAnnotationByText(propsText)
}

/**
 * 解析 vue 文件注释
 * @param {SFCDescriptor} descriptor vue格式化后的代码
 */
function relVueAnnotation(descriptor) {
    const source = descriptor.source
    const regex = /^<!--([\s\S]*?)-->/;
    const matches = source.match(regex);
    if (!matches || matches.length === 0) return ''
    const annotation = matches[0].substring(4, matches[0].length - 3)
    return annotation
}

exports.relPropsAnnotation = relPropsAnnotation;
exports.relVueAnnotation = relVueAnnotation;
